package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.UserLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {


    @Override
    public ResponseResult login(AdUserDto dto) {

        //1.参数校验
        if (StringUtils.isNotBlank(dto.getName()) || StringUtils.isNotBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.根据用户名查询用户信息
        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));

        //2.1 如果用户为null，提示用户不存在
        if (list == null || list.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

        //2.2 不为null 准备判断密码
        AdUser adUser = list.get(0);
        // 将用户输入的密码 加 salt 进行 md5加密 得到加密后的文件再和数据库密码进行对比
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());

        if (password.equals(adUser.getPassword())){

            Map map = new HashMap<>();

            // 一致
            String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
            //生成token 返回用户信息
            map.put("token",token);

            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);

            return ResponseResult.okResult(map);
        }else {
            // 不一致
            //返回密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
    }
}
